#include "io_context.h"
#include "../../log.h"

IOContextPool::IOContext& IOContextPool::GetIOService()
{
    auto& ctx  = m_io_contexts[m_ioc_index++];
    if(m_ioc_index == m_io_contexts.size())
    {
        m_ioc_index = 0;
    }
    return ctx;
}

void IOContextPool::Stop()
{
    for(auto& work: m_io_work)
    {
        work.reset();
    }

    for(auto& thread: m_threads)
    {
        thread.join();
    }
}

IOContextPool::IOContextPool(std::size_t thread_num)
:m_ioc_index(0)
,m_io_contexts(thread_num)
,m_io_work(thread_num)
{
    for(size_t i = 0; i < thread_num; ++i)
    {
        // 绑定work对象到io_context上
        m_io_work[i] = std::unique_ptr<IOContextPool::Work>(new IOContextPool::Work(m_io_contexts[i]));
    
        m_threads.emplace_back([this, i](){
            // 启动io_context
            m_io_contexts[i].run();
        });
    }
}

IOContextPool::~IOContextPool()
{
    log_info("IOContextPool::~IOContextPool, IOContextPool destructed");
    Stop();
}